#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include "RpcShell.hpp"
using namespace std;
enum MessageType
{
	LOGIN,
	LOGOUT,
	POLL,
	SEND
};
int main()
{
	RpcShell rpcShell;
	int sockfd = socket(AF_INET, SOCK_STREAM, 0);
	struct sockaddr_in ser;
	ser.sin_family = AF_INET;
	ser.sin_port = htons(8080);
	ser.sin_addr.s_addr = inet_addr("127.0.0.1");
	socklen_t len = sizeof(struct sockaddr_in);
	bind(sockfd, (struct sockaddr *)&ser, len);
	listen(sockfd, 5);
	while (1)
	{
		int n_sockfd;
		struct sockaddr_in cli;
		n_sockfd = accept(sockfd, (struct sockaddr *)&cli, &len);
		std::string id;
		while (true)
		{
			usleep(10 * 1000);
			char inBuffer[1024] = {0};
			int ret = read(n_sockfd, inBuffer, 1023);
			if (ret <= 0)
				continue;
			switch (inBuffer[0])
			{
			case LOGIN:
			{
				id = rpcShell.login();
				send(n_sockfd, id.c_str(), id.size(), 0);
			}
			break;
			case LOGOUT:
				break;
			case POLL:
			{
				std::string res = rpcShell.readShell(id);
				char buffer[] = {-1, 0};
				if (res.size())
				{
					write(n_sockfd, res.c_str(), res.size());
				}
				else
				{
					write(n_sockfd, buffer, 1);
				}
			}
			break;
			case SEND:
			{
				std::string data(inBuffer);
				data.erase(0, 1);
				rpcShell.writeShell(data, id);
				// std::string res = rpcShell.readShell(id);
				// send(n_sockfd, res.c_str(), res.size(), 0);
			}
			break;
			}
		}
		close(n_sockfd);
	}
}
